<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:doc="livcos.org/ns/doc"
  xmlns:c="livcos.org/ns/cosmos"
  xmlns:m="livcos.org/ns/map"
  xmlns:f="livcos.org/ns/xslt/function"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns="livcos.org/ns/map"
  exclude-result-prefixes="doc c f m xs">

	<xsl:import href="../../../../base.xsl"/>
	<xsl:import href="/livcos.org/common/default.xsl"/>
	
	<xsl:template match="m:item">
		<xsl:param name="level" as="xs:integer" tunnel="yes" select="0"/>
		<xsl:copy>
			<xsl:apply-templates select="@*"/>
			<xsl:if test="$level = 0">
				<map-title><xsl:value-of select="../../m:head/m:title"/></map-title>
			</xsl:if>
			<xsl:apply-templates select="node()"/>
		</xsl:copy>
	</xsl:template>

	<xsl:template match="m:*/@id">
		<xsl:attribute name="id">
			<xsl:value-of select="f:object-id(..)"/>
			<xsl:text>#</xsl:text>
			<xsl:value-of select="."/>
		</xsl:attribute>
	</xsl:template>
	
	<xsl:template match="m:rel">
		<xsl:param name="level" as="xs:integer" tunnel="yes" select="0"/>
		<xsl:if test="$level &lt; 2">
			<xsl:copy>
				<xsl:apply-templates select="@*"/>
				<xsl:if test="normalize-space(.) != ''">
					<comment>
						<xsl:value-of select="."/>
					</comment>
				</xsl:if>
				<xsl:variable name="uri" select="f:cosmos-uri(@ref, .)"/>
				<xsl:choose>
					<xsl:when test="f:object-available($uri/obj)">
						<xsl:variable name="item" select="doc($uri/obj)/*/*/*[@id = $uri/id]"/>
						<xsl:choose>
							<xsl:when test="$item">
								<xsl:apply-templates select="$item">
									<xsl:with-param name="level" select="$level + 1" tunnel="yes"/>
								</xsl:apply-templates>
							</xsl:when>
							<xsl:otherwise>
								<item missing="item">
									<label>!! Item not available !!</label>
								</item>
								<comment>
									<xsl:text>Item '</xsl:text>
									<xsl:value-of select="$uri/obj"/>#<xsl:value-of select="$uri/id"/>
									<xsl:text>' is not available!</xsl:text>
								</comment>
							</xsl:otherwise>
						</xsl:choose>
					</xsl:when>
					<xsl:otherwise>
						<item missing="map">
							<label>!! Map not available !!</label>
						</item>
						<comment>
							<xsl:text>Map for item '</xsl:text>
							<xsl:value-of select="$uri/obj"/>#<xsl:value-of select="$uri/id"/>
							<xsl:text>' is not available!</xsl:text>
						</comment>
					</xsl:otherwise>
				</xsl:choose>
			</xsl:copy>
		</xsl:if>
	</xsl:template>
	
</xsl:stylesheet>
